// pages/details/details.js

const WxParse = require('../wxParse/wxParse.js');
const share = require('../../components/utils.js')

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isactive: 0,
    ispayshows: false,
    shopdetails: '',
    goodsBannerList: [],
    imgurl: app.globalData.Imageurl,
    total: 1,
    type: 0,
    plshow: 3,
    showdj: true,
    showsj: false,
    showlogin: false,
    goodsCarNum: 0,
    isloadcomplete: true,
    autoplay: true,
    objectfit: 'contain',
    isvideopay: false,
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(' onLoad')

    console.log(options)
    
    this.setData({
      goodsId: options.goodsid
    })

    if(typeof(options.share)!='undefined'&& options.share=='share'){
      app.wxlogin().then(
        res=>{
          this.getGoodsDetails()
        })
       
    }else{
      this.getGoodsDetails()
    }
    

    this.videotext1 = wx.createVideoContext('video1')
  },

  bindVideoEnterPictureInPicture() {
    console.log('进入小窗模式')
  },
  bindchange(e) {
    // console.log(e.detail.current)
    if (this.data.isvideopay == true && e.detail.current == 0) {
      this.setData({
        autoplay: false,
      })
      this.videotext1.play()
    } else {
      this.setData({
        autoplay: true,
      })
      this.videotext1.pause()

    }
  },
  bindplayto(e) {
    console.log(e)
    this.setData({
      autoplay: false,
      isvideopay: true
    })
  },
  bindpause(e) {
    console.log(e)
    this.setData({
      autoplay: true,
    })
  },

  getPhoneNumber(e) {
    console.log(e)
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.request({
        url: app.globalData.Interfaceurl + 'grantWxMobile',
        method: "post",
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data: {
          userId: app.globalData.userId,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        },
        success: res => {
          console.log(res)
          wx.setStorageSync('mobile', JSON.parse(res.data.wxMobile).phoneNumber)
          console.log(wx.getStorageSync('mobile'))
          this.setData({
            showsj: false,
            showdj: true
          })

        }
      })
    }
  },

  // 商品详情图片过大处理
  replaceDetail(details) {
    var texts = ''; //待拼接的内容

    while (details.indexOf('<img') != -1) { //寻找img 循环
      texts += details.substring('0', details.indexOf('<img') + 4); //截取到<img前面的内容
      details = details.substring(details.indexOf('<img') + 4); //<img 后面的内容
      if (details.indexOf('style=') != -1 && details.indexOf('style=') < details.indexOf('>')) {
        texts += details.substring(0, details.indexOf('style="') + 7) + "max-width:100%;height:auto;margin:0 auto;"; //从 <img 后面的内容 截取到style= 加上自己要加的内容
        details = details.substring(details.indexOf('style="') + 7); //style后面的内容拼接
      } else {
        texts += ' style="max-width:100%;height:auto;margin:0 auto;" ';
      }
    }
    texts += details; //最后拼接的内容

    return texts

  },
  //截取vido
  dealvideo(richtext) {
    var imgReg = /<video.*?(?:>|\/>)/gi; //匹配所有img标签的正则表达式规则

    let contentArr = richtext.split(/<video[^>]*src=['"]([^'"]+)[^>]*><\/video>/)
    //var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; //匹配所有src地址的正则表达式规则
    var imgs = richtext.match(imgReg); //获取所有图片，格式为数组

    // let contentArr = richtext.replace(/<img/gi, '<img style="max-width:100%; height: auto"')
    // let contentArr = richtext.split(/<video[^>]*src=['"]([^'"]+)[^>]*><\/video>/)
    return imgs
  },
  cdealvideo(richtext) {
    let contentArr = richtext.replace(/<img/gi, '<img style="max-width:100%;height:auto"')
    contentArr = richtext.split(/<video [^>]*src=['"]([^'"]+)[^>]*><\/video>/)
    return contentArr
  },
  /**
   * 传数组e.currentTarget.dataset.imglist
   * 显示第几张e.currentTarget.dataset.current
   */
  enlargeimg(e) {
    var t = this

    console.log(e)
    var imglist = []
    if (e.currentTarget.dataset.type == 2) {
      e.currentTarget.dataset.imglist.forEach((element, index) => {
        imglist[index] = t.data.imgurl + element
      });
    } else {
      imglist[0] = t.data.imgurl + e.currentTarget.dataset.imglist
    }

    wx.previewImage({
      urls: imglist,
      current: t.data.imgurl + e.currentTarget.dataset.current,
    })
  },
  //显示所有评论{}
  showAppraiseList() {
    // this.setData({
    //   plshow:this.data.goodsAppraiseListlength
    // })
    if (this.data.goodsAppraiseNum != 0) {
      console.log(this.data.shopdetails.goodsAppraiseNum)
      wx.navigateTo({
        url: '/pages/comment/comment?goodsid=' + this.data.shopdetails.id,
      })

    } else {
      wx.showToast({
        title: '无商品评论',
        icon: 'none'
      })
    }

  },
  //评论图片放大
  showimg(e) {
    console.log(e)
    var t = this
    // console.log(e.currentTarget.dataset.imglist)
    var imglist = []
    e.currentTarget.dataset.imglist.forEach((element, index) => {
      imglist[index] = t.data.imgurl + element

    });
    wx.previewImage({
      urls: imglist,
      current: t.data.imgurl + e.currentTarget.dataset.imglist[e.currentTarget.dataset.indexs]

    })
  },
  //获取商品详情
  getGoodsDetails() {
    var t = this
    wx.request({
      url: app.globalData.Interfaceurl + 'getGoodsDetails',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        goodsId: t.data.goodsId
      },
      success: res => {
        console.log(res)
        // var shopdetail=t.cdealvideo(res.data.yeahcGoods.goodsIntroduce)
        var shopdetail = t.replaceDetail(res.data.yeahcGoods.goodsIntroduce)
        // var videodetailss=t.dealvideo(res.data.yeahcGoods.goodsIntroduce)
        // console.log(videodetailss)
        // console.log(shopdetail)


        t.setData({
          shopdetails: res.data.yeahcGoods,
          goodsBannerList: res.data.yeahcGoods.goodsBannerList,
          shoptext: shopdetail,
          goodsAppraiseList: res.data.goodsAppraiseList,
          goodsAppraiseListlength: res.data.goodsAppraiseList.length,
          goodsAppraiseNum: res.data.goodsAppraiseNum,
          goodsCarNum: wx.getStorageSync('userInfo') == '' ? 0 : res.data.goodsCarNum
        })
        console.log(res.data.yeahcGoods.goodsIntroduce)
        WxParse.wxParse('ActivitiesInfo', 'html', res.data.yeahcGoods.goodsIntroduce, t, 2)
        console.log(t.data.goodsAppraiseList)


      }
    })

  },

  //图片加载完成{
  bindloads(e) {
    if (e.currentTarget.dataset.imgid == 0) {
      this.setData({
        isloadcomplete: false
      })

    }

  },

  // 选择规格
  xzSpecifications(e) {

    // console.log(this.data.goodsSpec[e.currentTarget.dataset.id])
    this.setData({
      isactive: e.currentTarget.dataset.id,
      goodsSpecshow: this.data.goodsSpec[e.currentTarget.dataset.id],
      goodsspecStock: this.data.goodsSpec[e.currentTarget.dataset.id].specStock
    })
    if (this.data.goodsspecStock > 0) {
      this.setData({
        total: 1
      })
    } else {
      this.setData({
        total: 0
      })
    }
  },
  add() {
    if (this.data.total < this.data.goodsspecStock) {
      this.setData({
        total: this.data.total + 1
      })
    } else {
      wx.showToast({
        title: '库存不够了',
        icon: 'none'
      })
      this.setData({
        total: this.data.goodsspecStock
      })
    }

  },
  reduce() {
    if (this.data.goodsspecStock == 0) {
      return
    }
    if (this.data.total > 1) {
      this.setData({
        total: this.data.total - 1
      })

    } else {
      this.setData({
        total: 1
      })
    }

  },
  bindinput(e) {
    console.log(e)
    this.setData({
      total: e.detail.value
    })

  },

  bindblur(e) {
    if (this.data.goodsspecStock == 0) {
      wx.showToast({
        title: '缺货,无法发货',
        icon: 'none'
      })
      this.setData({
        total: 0
      })
      return
    }
    if (e.detail.value < 1) {
      this.setData({
        total: 1
      })

    }
    if (e.detail.value > this.data.goodsspecStock) {
      wx.showToast({
        title: '库存紧张，请重新输入',
        icon: 'none'
      })
      this.setData({
        total: 1
      })
    }
  },
  //立即购买
  ljshop() {
    this.getGoodsSpec(this.data.isactive)
    this.setData({
      ispayshows: true,
      type: 0
    })

  },
  //去登录
  gologin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  // 确认选择
  confirmselection() {
    if (wx.getStorageSync('userInfo') == '') {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {

      console.log(this.data.type)
      //类型为1--加入购物车 类型为0--立即购买
      if (this.data.goodsspecStock == 0) {
        wx.showToast({
          title: '该商品暂时缺货',
          icon: 'none',
          duration: 2000 //持续的时间
        })
        return
      }
      if (this.data.type == 1) {
        var t = this
        wx.request({
          url: app.globalData.Interfaceurl + 'saveGoodsCar',
          method: "post",
          header: {
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          data: {
            userId: app.globalData.userId,
            goodsId: t.data.goodsId,
            goodsSpecId: t.data.goodsSpecshow.id,
            goodsNum: t.data.total
          },
          success: res => {
            console.log(res)
            if (res.statusCode == 200 && res.data.result == 0) {
              t.setData({
                ispayshows: false,
                goodsCarNum: this.data.goodsCarNum + 1
              })
              wx.showToast({
                title: '添加成功',
                icon: 'success',
                duration: 2000,
              })


            } else {
              t.setData({
                ispayshows: false
              })
              wx.showToast({
                title: '添加失败',
                icon: "error",
                duration: 2000
              })

            }
          }
        })
      } else {



        wx.navigateTo({
          url: '/pages/porder/porder?goodsSpec=' + JSON.stringify(this.data.goodsSpecshow) + '&goodsNumber=' + this.data.total + '&type=0' + '&goodsId=' + this.data.goodsId,
        })

      }
    }
    // this.setData({
    //   ispayshows:false
    // })
  },
  // 获取规格
  getGoodsSpec(isactive) {
    var t = this

    wx.request({
      url: app.globalData.Interfaceurl + 'getGoodsSpec',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        goodsId: t.data.goodsId
      },
      success: res => {
        console.log(res)
        t.setData({
          goodsSpec: res.data.goodsSpec,
          goodsSpecshow: res.data.goodsSpec[t.data.isactive],
          goodsspecStock: res.data.goodsSpec[t.data.isactive].specStock,
        })


      }
    })
  },
  // 选择规格
  xzguige() {
    //商品规格
    this.getGoodsSpec(this.data.isactive)

    this.setData({
      ispayshows: true,

    })

  },
  // 关闭规格
  offSpecifications() {
    this.setData({
      ispayshows: false
    })
  },
  //加入购物车
  goshopcart() {

    this.getGoodsSpec(this.data.isactive)
    this.setData({
      ispayshows: true,
      type: '1',
    })
  },
  //去首页
  goindex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  goshoppingcart() {
    wx.reLaunch({
      url: '/pages/shoppingcart/shoppingcart',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('userInfo') == "") {
      this.setData({
        showdj: false,
        showsj: false,
        showlogin: true,
      })

    } else if (wx.getStorageSync('mobile') == '') {
      this.setData({
        showsj: true,
        showdj: false,
        showlogin: false,
      })
    } else {
      this.setData({
        showsj: false,
        showdj: true,
        showlogin: false,
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var t=this
    
    // goodsId:options.goodsid
    return share.share('好运牛家用平板手推车\r\n一键全折叠 省力省空间', '/pages/details/details?goodsid=' + t.data.goodsId+'&share=share', '../../images/share.jpg')
  }
})